#!/usr/bin/env python3
# TOOLS/register.py - 更新 INDEX/index.json（追加记录 + SHA256）
import sys, os, json, hashlib, time

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
INDEX = os.path.join(ROOT, "INDEX", "index.json")

def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            h.update(chunk)
    return h.hexdigest()

def main():
    with open(INDEX, "r", encoding="utf-8") as f:
        idx = json.load(f)
    idx["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S+08:00", time.localtime())
    files = []
    for base, _, names in os.walk(ROOT):
        if os.path.basename(base) in ("INDEX", "TOOLS"): 
            # 仍纳入索引以便完整性校验（也可排除）
            pass
        for n in names:
            path = os.path.join(base, n)
            if not os.path.isfile(path): 
                continue
            rel = os.path.relpath(path, ROOT)
            sha = sha256_of(path)
            files.append({"path": rel, "sha256": sha, "size": os.path.getsize(path)})
    idx["files"] = files
    with open(INDEX, "w", encoding="utf-8") as f:
        json.dump(idx, f, ensure_ascii=False, indent=2)
    print(f"INDEX updated: {len(files)} files")

if __name__ == "__main__":
    main()
